package com.apple1.blogweb.config;
 
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
 
/**
 * 此方法不是最佳的办法，但是目前可以工作
 * 最好的办法是使用FastJons针对Springboot2.0的starter
 * @author Henry
 * 2018/12/21
 *
 */
@Configuration
public class FastJsonWebConfig implements WebMvcConfigurer {
    
    @Value("${fastjson.dateformat}")
    private String dateFormat;
 
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
 
        FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
 
        // 处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastJsonConverter.setSupportedMediaTypes(fastMediaTypes);
        fastJsonConfig.setCharset(Charset.forName("UTF-8"));
 
        fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect,
                // SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullListAsEmpty, 
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullBooleanAsFalse);
        fastJsonConfig.setDateFormat(dateFormat);
        
        fastJsonConverter.setFastJsonConfig(fastJsonConfig);
 
        // 替换MappingJackson2HttpMessageConverter
        for (int i = 0; i < converters.size(); i++) {
            if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) {
                converters.set(i, fastJsonConverter);
            }
        }
    }
 
}
